#include "item.h"
#include <QPalette>
#include <QDebug>
#include <QColor>
#include <dialog.h>
/*Item::Item(QWidget *parent,QString content,QDateTime datetime) : QWidget(parent)
{
    this->content=new QLabel(content);
    endTime=new QLabel(datetime.toString("yyyy-MM-dd hh:mm:ss"));
    checkBox=new QCheckBox;
    pushButton=new QPushButton(tr("进入倒计时"));
    layout=new QHBoxLayout(this);
    layout->setSpacing(10);
    layout->addWidget(this->content);
    layout->addWidget(endTime);
    layout->addWidget(checkBox);
    layout->addWidget(pushButton);
}*/

Item::Item(QWidget *parent, ItemDao::ItemData data,QVBoxLayout * listP) : QWidget(parent)
{
    this->data=data;
    content=new QLabel(data.content);
    endTime=new QLabel(data.dateTime);
    checkBox=new QCheckBox;
    pushButton=new QPushButton(tr("进入倒计时"));
    layout=new QHBoxLayout(this);
    layout->setSpacing(10);
    layout->addWidget(this->content);
    layout->addWidget(endTime);
    layout->addWidget(checkBox);
    layout->addWidget(pushButton);
    connect(checkBox,SIGNAL(clicked()),this,SLOT(pressCheck()));
    connect(pushButton,SIGNAL(clicked(bool)),this,SLOT(startClock()));
    this->listP=listP;
    parentP=parent;
 //   setGeometry(0, 0, 300, 100);


}

void Item::pressCheck()
{
    if(QMessageBox::question(this,tr("确认"),tr("您确认事情已经做完了吗？"),QMessageBox::Ok|QMessageBox::Cancel)==QMessageBox::Ok)
    {
        //qDebug()<<"点击完成";
        ItemDao itemDao;
        itemDao.finishItem(getItemId(),1);
        listP->removeWidget(this);
        this->deleteLater();

    }
    else
    {
        checkBox->setCheckState(Qt::Unchecked);
    }
}

long Item::getRestSecond()
{
    QString dataTimeStr=data.dateTime;
    QDateTime dateTime=QDateTime::fromString(dataTimeStr,"yyyy-MM-dd hh:mm:ss");
    long end=dateTime.toTime_t();
    long start=QDateTime::currentDateTime().toTime_t();
    return end-start;
}

int Item::getItemId()
{
    return this->data.id;
}

void Item::setCondition(int value)
{
    QColor color;
    color.setRgb(255,0,0,value);
    QPalette pal(this->palette());
    pal.setColor(QPalette::Background,color);
    pal.setColor(QPalette::Button,color);
    setAutoFillBackground(true);
    setWindowOpacity(0.4);
    setPalette(pal);
}

void Item::startClock()
{
    long restTime=getRestSecond();
    if(restTime>86400)
    {
        QMessageBox::critical(this,"警告","超过一天的任务无法进行倒计时",QMessageBox::Ok);
        return;
    }
    DlgClock * clock=new DlgClock(NULL,restTime,pushButton);
    this->pushButton->setEnabled(false);//设置按钮不可用
    clock->show();
}
